var C = {
	flag : true,
	confirm : function(msg, back) {
		if (confirm(msg))
		{
			back();
		}
	},
	getUrl : function(url, params){  //生成网址
	    if (params)
	    {
	    	url += "?" + params;
	    }

	    return url; 
    },
	post : function(url, data, back) {
		if (!this.flag)
		{
			return false;
		}
		
		this.flag = false;
		var self = this; 
		$.post(url, data, function(json) {
			self.flag = true;
			 
			if (!json)
			{
				return $.alert('您没有权限');
			}
			
			if (json.ret != "0")
			{
				$.alert(json.msg);
			}
			else
			{
				back(json.data);
			}
		}, 'JSON');
	},
	getForm : function(name) {  //得到表單數據
		var elements = document.getElementById(name).elements;
		if (!elements) {
			return false;
		}

		var data = {};
		for ( var i = 0; i < elements.length; i++) {
			var formType = elements[i].nodeName;
			var value = elements[i].value;
			var formName = elements[i].name;

			if (!formName)
			{
				continue;
			}
			switch (formType) {
			case "INPUT":
				switch (elements[i].type.toLowerCase()) {
				case "text":
				case "password":
				case "submit":
				case "button":
				case "reset":
				case "hidden":
					if (data[formName] && value != "") {
						data[formName] += "," + value;
					} else {
						data[formName] = value;
					}
					break;
				case "radio":
				case "checkbox":
					if (elements[i].checked) {
						if (data[formName] && value != "") {
							data[formName] += "," + value;
						} else {
							data[formName] = value;
						}
					}
					break;
				default:
					break;
				}
				break;

			case "SELECT":
			case "TEXTAREA":
				data[formName] = data[formName] ? data[formName] + "," + value
						: value;
				break;
			case "BUTTON":
			case "submit":
			case "button":
			case "reset":
				data[formName] = value;
				break;
			break;
		default:
			break;
		}
	}

	return data;
   }
};

var Picture = function(option) {
	this.option = option;
	this.swfu = "";	
	this.init();
}

$.extend(Picture.prototype, {
	limit : 1,
	step : "",
	name : "",
	max : 0,
	queue : 0,
	id : 0,
	backtype : "",
	mod : 0,
	init : function() {
		this.name = this.option.name ? this.option.name : "thumb";
		this.backtype = this.option.backtype ? this.option.backtype : "auto";
		this.initHtml();
		this.initList(this.option.data ? this.option.data : []);
		
	    this.step = this.name + "_step";
	    this.mod = this.limit;
	    this.max = this.limit;	    
	    var url = this.option.url ? this.option.url : this.getUrl();
	    var settings = {
			flash_url :"/st/js/swfupload/swfupload.swf",
			upload_url: url,	
			post_params: {
				"token" : C.token
		    },
			file_size_limit : "1024 KB",
			file_types : this.option.type,
			file_types_description : this.option.type.replace(/;/, ","),
			file_upload_limit : 0,  //配置上传个数
			file_queue_limit : 0,
			debug: false, 
		
			// Button settings
			button_image_url: this.name == "fileurl" ? "/st/images/choose_file.jpg" : "/st/images/choose_img.jpg",
			button_width: "76",
			button_height: "23",
			button_placeholder_id: this.name + "_choose",
			button_window_mode: "transparent",
			button_cursor : SWFUpload.CURSOR.HAND,
			
			file_queued_handler : $.apply(this, this.fileQueued),
			file_queue_error_handler : $.apply(this, this.fileQueueError),
			//file_dialog_complete_handler : fileDialogComplete,
			upload_start_handler : $.apply(this, this.uploadStart),
			upload_progress_handler : $.apply(this, this.uploadProgress),
			upload_error_handler : $.apply(this, this.uploadError),
			upload_success_handler : $.apply(this, this.uploadSuccess),
			upload_complete_handler : $.apply(this, this.uploadComplete)
		//queue_complete_handler : flashUpload.queueComplete	
		};	

		this.swfu = new SWFUpload(settings);	
		if (this.limit == 0)
		{
			$.show($("#"+this.name+"_nochoose"));
		}

    }, 
    initHtml : function() {
    	var id = this.name;
    	var string = '<div class="file"><input type="hidden" name="' + id + '" id="' + id + '" value="" />';
        string += '<div style="float: left; margin-top: 10px;" ><div id="' + id + '_choose" class="choose" ></div></div><div class="nochoose" id="' + id + '_nochoose" style="display: none;"></div>';
        string += ' <div class="step" id="' + id + '_step" style="float: left; margin-left: 10px;"></div> <ul style="clear: both;" id="' + id + '_img_list"> </ul></div>';
        $("#" + id + "_content").innerHTML = string;
        
    },
    
    fileQueued : function(file) {
    	this.queue++;
	    this.swfu.startUpload();
   },
   fileQueueError : function(file, code) {
	   if (code != -100)
       {		   
		   alert(this._getError(code));
       }
       else
       {
    	   alert("只能上传"+this.max+"张图片");
       }
   },
   uploadStart : function(file) {	   
   },
   uploadProgress : function(file, bytesLoaded, bytesTotal) {
   	   var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
       $("#"  + this.step).innerHTML = "上传" + percent.toString() + "%"; 
   },
   uploadError : function(file, code, msg) {
	   alert("上传失败");
   },
   uploadSuccess : function(file, data) {
	  //$.hide($("#nochoose"));
	   var self = this;
	   var json = data.parseJSON();
	   
	   if (json.ret != '0')
	   {
		   this.limit++;
		   //this.swfu.setFileUploadLimit(this.limit);	   
		   alert(json.msg);	   
	   }
	   else
	   {
		   var row = json.data;
		   this.add(row);
	   }

   },
   add : function(row) {
	   console.log(row);
	   //alert(row);
	   if (this.backtype == "more")
	   {
		   this.backMore(row);
	   }
	   else if (this.backtype == "file")
	   {
		   this.backFile(row);
	   }
	   else
	   {
		   var self = this;
		   var li = document.createElement("li");
		   var id = new Date().getTime();
		   var url = row.url;
	
		   li.id = "li_pic" + id
		   var string = '<a href="'+row.url+'" target="_blank" ><img src="'+url+'" style="max-width: 200px;" /></a><p></p>';
		   li.innerHTML = string;
		   li.setAttribute("value", row.url);
		   var img = $("#" + this.name + "_img_list");
		   img.innerHTML = '';
		   img.appendChild(li);
		   /**
		   var fun = function() {
			   C.confirm("你确定要删除吗？", function() {
				   self.delFile("li_pic" + id, row.url);
			   });	   
		   }
		   
		   $("#del_img_" + row.id).onclick = fun;  
		   **/ 
		   $("#" + this.name).value = row.url;  
	   }
	  
   },
   backMore : function(row) {
	   var self = this;
	   var li = document.createElement("li");
	   li.id = "li_pic" + row.id
	   var string = '<a href="'+row.url+'" target="_blank" ><img src="'+row.url+'" height="100" /></a><p><a href="javascript:;" id="del_img_'+row.id+'" >删除</a></p>';
	   li.innerHTML = string;
	   var autovalue = row.id;
	   li.setAttribute("value", autovalue);
	   var img = $("#" + this.name + "_img_list");
	   img.appendChild(li);
	   var fun = function() {
		   C.confirm("你确定要删除吗？", function() {
			   self.delFile("li_pic" + row.id, autovalue);
		   });	   
	   }
	   
	   $("#del_img_" + row.id).onclick = fun;   
	   var value = $("#" + this.name).value;
	   $("#" + this.name).value += value ? ',' + autovalue : autovalue;	   	   
   },
   backFile : function(row) {
	   var self = this;
	   var li = document.createElement("li");
	   var id = new Date().getTime();
	   var url = row.url;

	   li.id = "li_pic" + id
	   var string = '<a href="'+row.url+'" target="_blank" >' + row.name + '</a><p></p>';
	   li.innerHTML = string;
	   li.setAttribute("value", row.url);
	   var img = $("#" + this.name + "_img_list");
	   img.innerHTML = '';
	   img.appendChild(li); 
	   $("#" + this.name).value = row.url;     
   },
   uploadComplete : function() {
	   this.queue--;
	   if (this.queue > 0)
	   {
		   this.swfu.startUpload();		   
	   }	 
	   else
	   {
		   $.hide($("#"+this.name+"_nochoose"));
	   }
   },
   delFile : function(id, path) {
	   this.limit++;
	   this.swfu.setFileUploadLimit(this.limit);	
	   C.removeTag($("#" + id));
	   $.hide($("#"+this.name+"_nochoose"));
	   this.removeId(path);
   },
   removeId : function(path) {
	   var idObj = $("#" + this.name);
	   var value = idObj.value.split(",");
	   var list = new Array();
	   for (var i = 0; i < value.length; i++)
	   {
		   if (value[i] != path)
		   {
			   list.push(value[i]);
		   }
	   }
	   idObj.value = list.length == 0 ? "" : list.join(',');
   },
   getUrl : function() {
	   var url;
	   switch (this.name)
	   {	  
	       case 'fileurl' : 
	    	    url = "/upload/file";
	        	break;
	    	default : 
	    		url = "/upload/image";
	    		break;
	   }

	   return url;
   },
   initList : function(data) {
	   if (data.length == 0)
	   {
		   return true;
	   }

	   for (var i = 0; i < data.length; i++)
	   {
		   this.add(data[i]);
	   }
   },
   _getError : function(code) {  //通过错误码得到错误信息 
       var value = "";
       switch (code)
       {
           case -100 :
               value = "一次只能上传10张图片";
               break;
           case -110 : 
               value = "图片超过1M";
               break;
           case -120 :
               value = "无法上传零字节的图片";
               break;    
           case -130:
               value = "不支持的该文件类型";
               break;    
           default :
               value = "";
               break;    
       }

       return value;
   }
	
})

var File = function(id, data) {
	var config = {
         name : id , "type" : "*.rar;*.zip;*.png;*.jpg;*.gif;*.doc;*.pdf;*.docx;*.wps;*.xls", backtype : "file"
     }
     config.data = data;
     var picture = new Picture(config);
}


C.choose = function(name, obj){  //全选，反选
    var list = document.getElementsByName(name);
    var ischecked = true;
    var noall = obj.getAttribute('noall');

    if(noall == 'yes')
    {
    	ischecked = false;
    	obj.setAttribute('noall', 'no');
    }
    else
    {
    	ischecked = true;
    	obj.setAttribute('noall', 'yes');
    }
    
    for (var i = 0; i < list.length; i++)
    {
    	list[i].checked = ischecked;
    }
}

C.mDelete = function(url) {
	this.mHandle(function(id) {
		C.confirm("您确定要删除所选吗？", function() {
        	C.post(url, {"id" : id}, function() {
        		location.reload();
        	});
        }) 
	})
}
C.mHandle = function(back) {
	var list = document.getElementsByName("id[]");
	var data = new Array();
    for (var i = 0; i < list.length; i++)
    {
    	if (list[i].checked)
    	{
    		data.push(list[i].value);
    	}
    }

    if (data.length == 0)
    {
    	$.alert("至少选择一条信息");
    	return false;
    }
    
    var id = data.join(',');
    back(id);
}